package Reproductor;

import com.prueba.MotorDJ;
import java.awt.Color;
import java.awt.Event;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Random;
import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;

import java.sql.*;
import java.util.Map;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.UnsupportedLookAndFeelException;
import jess.JessException;
import org.tritonus.share.sampled.TAudioFormat;
import org.tritonus.share.sampled.file.TAudioFileFormat;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Pablo
 */
public class ReproductorFinal extends javax.swing.JFrame {

    private String filename= "" ;
    MP3AD track = new MP3AD(filename);
    private DefaultListModel df = new DefaultListModel();
    //private String[] tracks = new String[100];
    //private String[] titles = new String[100];
    //private long[] pesos = new long[100];
    private ArrayList<String> rutas = new ArrayList(30);
    private ArrayList<String> archivos = new ArrayList(30);
    private ArrayList<Long> tamaños = new ArrayList(30);    
    private ArrayList<Long> duraciones = new ArrayList(30);
    private ArrayList<String> artistas = new ArrayList(30);
    private ArrayList<String> titulos = new ArrayList(30);
    private ArrayList<String> albums = new ArrayList(30);
    private ArrayList<Long> frecuencias = new ArrayList(30);
    private ArrayList<Long> bitrates = new ArrayList(30);
    private ArrayList<String> caratulas = new ArrayList(30);
    private int cont=0, index=0;
    private FileChooser selector;
    private long duracion;
    int sw=0, sw2=0; 
    Cronometro reloj;
    int nroActual=0, nroAnterior=0;
    float volumen;
    Thread hilo;
    private final int mil = 1000;
    private Random indicesAleatorios = new Random();
    private int indexAleatorio;
    private boolean aleatorio = false;
    private boolean ultimo = false;
    private boolean repetirLista = false;
    private Connection conn;
    private Statement stmt;
    ResultSet rs;
    private volatile int a = 1000;
    MotorDJ motor ;
       
    public ReproductorFinal() throws JessException {
        initComponents();
        try {
            conectar();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ReproductorFinal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(ReproductorFinal.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.setSize(652,475);  
        this.setLocationRelativeTo(null);
        reloj = new Cronometro();
        reloj.setVisible(true);                    
        reloj.setBounds(98, 26, 98, 52);        
        add(reloj); 
        motor = new MotorDJ();
    }
    
    public void conectar() throws ClassNotFoundException, SQLException{
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/","root","admin");
        stmt = conn.createStatement();
        try{
            stmt.executeUpdate("CREATE DATABASE songs2");
        }
        catch(SQLException e){ }        
        stmt.execute("USE songs2");
        try{
            stmt.executeUpdate("CREATE TABLE lista (idSong int not null,Artista varchar(80),"
                    + "Titulo varchar(100),Album varchar(50),Genero varchar(30),Año int,Bitrate int,"
                    + "Frecuencia int,Duracion long,Tamaño long,Archivo varchar(100),Ruta varchar(100),"
                    + "Compositor varchar(80),Imagen varchar(80), constraint claveLista primary key (idSong))");
        }
        catch (SQLException e){ }
        this.inicializarArrays();
        //this.desconectar();
    }
    
    public void inicializarArrays() throws SQLException{
        stmt = conn.createStatement(); 
        rs = stmt.executeQuery( "SELECT Artista, Titulo, Album, Bitrate, Frecuencia, Tamaño, Archivo, Ruta, Duracion, Imagen FROM lista"); 
        while (rs.next()) { 
            artistas.add(rs.getString("Artista"));
            titulos.add(rs.getString("Titulo"));
            albums.add(rs.getString("Album"));
            bitrates.add(rs.getLong("Bitrate"));
            frecuencias.add(rs.getLong("Frecuencia")/1000);
            duraciones.add(rs.getLong("Duracion"));
            tamaños.add(rs.getLong("Tamaño"));
            archivos.add(rs.getString("Archivo")); 
            rutas.add(rs.getString("Ruta"));             
            caratulas.add(rs.getString("Imagen"));
            //pesos.add(rs.getLong("peso"));        
            filename = rs.getString("Ruta");
            cont++;
            lista.setListData(archivos.toArray());
            if(cont==1){
                track = new MP3AD(filename);
            }
            if(lista.getSelectedIndex()==-1){
                lista.setSelectedIndex(0);
            }
        }
    }
    
    public void desconectar() throws SQLException{            
        rs.close(); 
        stmt.close(); 
        conn.close();
    }
            
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        open = new javax.swing.JButton();
        previous = new javax.swing.JButton();
        play = new javax.swing.JButton();
        next = new javax.swing.JButton();
        stop = new javax.swing.JButton();
        pantalla = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        lista = new javax.swing.JList()
        ;
        timeDesp = new javax.swing.JSlider();
        timeDesp.setValue(0);
        timeDesp.setPaintTicks(false);
        timeDesp.setPaintTrack(true);
        ;
        remove = new javax.swing.JButton();
        equalizador = new javax.swing.JLabel();
        random = new javax.swing.JButton();
        repetir = new javax.swing.JButton();
        volDesp = new javax.swing.JSlider();
        volDesp.setValue(100);
        volDesp.setMaximum(100);
        volDesp.setPaintTicks(false);
        volDesp.setPaintTrack(true);
        Volumen.setVolumen(1);
        ;
        imagen = new javax.swing.JLabel();
        Panel = new javax.swing.JPanel();
        artista = new javax.swing.JLabel();
        titulo = new javax.swing.JLabel();
        album = new javax.swing.JLabel();
        extras = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        lugar_cbx = new javax.swing.JComboBox();
        elegirMusica_btn = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        tipoEv_cbx = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        cantPer_cbx = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        edadProm_cbx = new javax.swing.JComboBox();
        jButton2 = new javax.swing.JButton();
        hora_cbx = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        generoM_cbx = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("XpertDJ");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);
        getContentPane().setLayout(null);

        open.setIcon(new javax.swing.ImageIcon(getClass().getResource("/add.png"))); // NOI18N
        open.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openActionPerformed(evt);
            }
        });
        getContentPane().add(open);
        open.setBounds(15, 321, 42, 20);

        previous.setIcon(new javax.swing.ImageIcon(getClass().getResource("/previous.png"))); // NOI18N
        previous.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                previousActionPerformed(evt);
            }
        });
        getContentPane().add(previous);
        previous.setBounds(109, 101, 44, 24);

        play.setIcon(new javax.swing.ImageIcon(getClass().getResource("/play.png"))); // NOI18N
        play.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                playActionPerformed(evt);
            }
        });
        getContentPane().add(play);
        play.setBounds(157, 93, 40, 40);

        next.setIcon(new javax.swing.ImageIcon(getClass().getResource("/next.png"))); // NOI18N
        next.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextActionPerformed(evt);
            }
        });
        getContentPane().add(next);
        next.setBounds(201, 103, 44, 23);

        stop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/stop.png"))); // NOI18N
        stop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stopActionPerformed(evt);
            }
        });
        getContentPane().add(stop);
        stop.setBounds(69, 102, 28, 22);

        pantalla.setBackground(new java.awt.Color(255, 255, 255));
        pantalla.setFont(new java.awt.Font("BankGothic Lt BT", 0, 12)); // NOI18N
        pantalla.setForeground(new java.awt.Color(255, 255, 255));
        pantalla.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        pantalla.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        pantalla.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        getContentPane().add(pantalla);
        pantalla.setBounds(203, 60, 143, 19);

        jScrollPane2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jScrollPane2.setViewportBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        DefaultListModel model = new DefaultListModel();
        lista.setBackground(new java.awt.Color(204, 204, 204));
        lista.setModel(model);
        lista.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lista.setSelectionBackground(new java.awt.Color(255, 255, 255));
        lista.setSelectionForeground(new java.awt.Color(55, 120, 209));
        lista.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listaMouseClicked(evt);
            }
        });
        lista.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listaValueChanged(evt);
            }
        });
        lista.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(lista);

        getContentPane().add(jScrollPane2);
        jScrollPane2.setBounds(7, 170, 342, 145);

        timeDesp.setBackground(new java.awt.Color(75, 75, 98));
        timeDesp.setForeground(new java.awt.Color(153, 255, 51));
        timeDesp.setPaintTicks(true);
        timeDesp.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                timeDespMouseClicked(evt);
            }
        });
        timeDesp.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                timeDespStateChanged(evt);
            }
        });
        timeDesp.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                timeDespMouseDragged(evt);
            }
        });
        getContentPane().add(timeDesp);
        timeDesp.setBounds(10, 78, 333, 20);

        remove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/remove.png"))); // NOI18N
        remove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeActionPerformed(evt);
            }
        });
        getContentPane().add(remove);
        remove.setBounds(73, 316, 44, 22);
        getContentPane().add(equalizador);
        equalizador.setBounds(9, 34, 88, 36);

        random.setIcon(new javax.swing.ImageIcon(getClass().getResource("/random.png"))); // NOI18N
        random.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                randomActionPerformed(evt);
            }
        });
        getContentPane().add(random);
        random.setBounds(290, 102, 28, 22);

        repetir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/repetir.png"))); // NOI18N
        repetir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                repetirActionPerformed(evt);
            }
        });
        getContentPane().add(repetir);
        repetir.setBounds(258, 101, 26, 24);

        volDesp.setBackground(new java.awt.Color(31, 35, 72));
        volDesp.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                volDespMouseClicked(evt);
            }
        });
        volDesp.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                volDespMouseDragged(evt);
            }
        });
        getContentPane().add(volDesp);
        volDesp.setBounds(233, 31, 110, 20);
        getContentPane().add(imagen);
        imagen.setBounds(0, -2, 0, 350);

        Panel.setBackground(new java.awt.Color(202, 199, 199));
        Panel.setLayout(null);

        artista.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        artista.setForeground(new java.awt.Color(31, 40, 95));
        artista.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        artista.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        Panel.add(artista);
        artista.setBounds(0, 0, 190, 30);

        titulo.setForeground(new java.awt.Color(24, 58, 154));
        titulo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        titulo.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        Panel.add(titulo);
        titulo.setBounds(0, 30, 190, 30);

        album.setForeground(new java.awt.Color(24, 58, 154));
        album.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        album.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        Panel.add(album);
        album.setBounds(0, 60, 190, 30);

        extras.setForeground(new java.awt.Color(24, 58, 154));
        extras.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        extras.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        Panel.add(extras);
        extras.setBounds(0, 90, 190, 30);

        getContentPane().add(Panel);
        Panel.setBounds(356, 0, 190, 120);

        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Lugar");
        jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, -1, -1));

        lugar_cbx.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Discoteca", "Local", "Playa", "Casa", "Patio" }));
        jPanel1.add(lugar_cbx, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 20, 90, -1));

        elegirMusica_btn.setText("Elegir música");
        elegirMusica_btn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                elegirMusica_btnActionPerformed(evt);
            }
        });
        jPanel1.add(elegirMusica_btn, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 220, 100, -1));

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setText("Tipo de Evento");
        jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 50, -1, -1));

        tipoEv_cbx.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Cumpleaños", "AniversarioBodas", "Matrimonio", "Despedida", "Quinceañero" }));
        jPanel1.add(tipoEv_cbx, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 50, 90, -1));

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setText("Hora");
        jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 90, -1, -1));

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel5.setText("Cantidad de Personas");
        jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 120, -1, -1));

        cantPer_cbx.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "10", "15", "20", "30", "40", "50", "150", "400", "800", "1000" }));
        jPanel1.add(cantPer_cbx, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 120, 90, -1));

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel6.setText("Edad Promedio (años)");
        jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 160, -1, -1));

        edadProm_cbx.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "12", "15", "16", "18", "20", "23", "26", "28", "30", "32", "35", "40", "45", "50", "60" }));
        jPanel1.add(edadProm_cbx, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 160, 90, -1));

        jButton2.setText("Salir");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 220, 80, -1));

        hora_cbx.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "00:00", "00:30", "01:00", "01:30", "02:00", "02:30", "03:00", "03:30", "04:00", "04:30", "05:00", "05:30", "06:00", "06:30", "07:00", "07:30", "16:00", "16:30", "17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "20:00", "20:30", "21:00", "21:30", "22:00", "22:30", "23:00", "23:30" }));
        jPanel1.add(hora_cbx, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 90, 90, -1));

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setText("Género Mayoritario");
        jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 190, -1, -1));

        generoM_cbx.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Ninguno", "Masculino", "Femenino" }));
        jPanel1.add(generoM_cbx, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 190, 90, -1));

        getContentPane().add(jPanel1);
        jPanel1.setBounds(360, 130, 250, 250);

        jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/repro1.png"))); // NOI18N
        jLabel8.setText("jLabel8");
        getContentPane().add(jLabel8);
        jLabel8.setBounds(0, 0, 360, 350);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void openActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openActionPerformed
        String key, valArtista=null, valTitulo=null, valAlbum=null, valArchivo, valRuta; //valRuta: ruta corregida para la BD
        Long valDuracion=0L, valFrecuencia=0L, valTamaño, valBitrate = 0L;
        Integer valAño=0;
        selector = new FileChooser();
        filename = selector.getNameFile().toString();
        rutas.add(filename);
        valRuta = CorregirRuta.getRutaCorregida(filename);
        valArchivo=selector.getNameFile().getName();
        archivos.add(valArchivo);
        valTamaño=selector.getTamañoFile();
        tamaños.add(valTamaño/1000);
        cont++;
        lista.setListData(archivos.toArray());
        
        //LEYENDO ID3
        File file = new File(filename);
        AudioFileFormat baseFileFormat = null;
        AudioFormat baseFormat = null;
        try {
            baseFileFormat = AudioSystem.getAudioFileFormat(file);
        } catch (UnsupportedAudioFileException ex) {
            Logger.getLogger(MP3AD.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MP3AD.class.getName()).log(Level.SEVERE, null, ex);
        }
        baseFormat = baseFileFormat.getFormat();
        // TAudioFileFormat properties
        if (baseFileFormat instanceof TAudioFileFormat) {
            Map properties = ((TAudioFileFormat)baseFileFormat).properties();
            key = "author";
            valArtista = (String) properties.get(key);
            artistas.add(valArtista);
            key = "title";
            valTitulo = (String) properties.get(key);
            titulos.add(valTitulo);
            key = "album";
            valAlbum = (String) properties.get(key);
            albums.add(valAlbum);
            key = "duration";
            valDuracion = ((Long) properties.get(key))/1000000;
            duraciones.add(valDuracion);
            key = "date";
            if((String)properties.get(key)!=null && !((String)properties.get(key)).equals("")){
                valAño = Integer.parseInt((String)properties.get(key));      
            }            
        }      
        // TAudioFormat properties
        if (baseFormat instanceof TAudioFormat) {
             Map properties = ((TAudioFormat)baseFormat).properties();
             key = "bitrate";
             String br = String.valueOf((Integer) properties.get(key)/1000);
             valBitrate = Long.parseLong(br);
             bitrates.add(valBitrate);
             valFrecuencia = ((long)((TAudioFormat)baseFormat).getSampleRate())/1000;
             frecuencias.add(valFrecuencia);
        }
        caratulas.add(null);
        
        //GUARDANDO EN BASE DE DATOS
        try {
            stmt = conn.createStatement(); 
            String instruccion = "INSERT INTO lista VALUES("+cont+", '"+valArtista+"', '"+valTitulo+
                    "', '"+valAlbum+"','"+null+"',"+valAño+" ,"+valBitrate+","+valFrecuencia+","+valDuracion+
                    ","+valTamaño+",'"+valArchivo+"', '"+valRuta+"','"+null+"','"+null+"')";
//            stmt.execute(instruccion); //null: genero y compositores 
        } catch (SQLException ex) {
            Logger.getLogger(ReproductorFinal.class.getName()).log(Level.SEVERE, null, ex);
        }        
        
        if(cont==1){
            track = new MP3AD(filename);            
        }
        if(lista.getSelectedIndex()==-1){
            lista.setSelectedIndex(0);
        }
    }//GEN-LAST:event_openActionPerformed

    private void agregarALista(String filename){
        String key, valArtista=null, valTitulo=null, valAlbum=null, valArchivo, valRuta; //valRuta: ruta corregida para la BD
        Long valDuracion=0L, valFrecuencia=0L, valTamaño, valBitrate = 0L;
        Integer valAño=0;
        
        rutas.add(filename);
        valArchivo=filename.substring(10);
        archivos.add(valArchivo);
        cont++;
        lista.setListData(archivos.toArray());
        
        //LEYENDO ID3
        File file = new File(filename);
        AudioFileFormat baseFileFormat = null;
        AudioFormat baseFormat = null;
        try {
            baseFileFormat = AudioSystem.getAudioFileFormat(file);
        } catch (UnsupportedAudioFileException ex) {
            Logger.getLogger(MP3AD.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MP3AD.class.getName()).log(Level.SEVERE, null, ex);
        }
        baseFormat = baseFileFormat.getFormat();
        // TAudioFileFormat properties
        if (baseFileFormat instanceof TAudioFileFormat) {
            Map properties = ((TAudioFileFormat)baseFileFormat).properties();
            key = "author";
            valArtista = (String) properties.get(key);
            artistas.add(valArtista);
            key = "title";
            valTitulo = (String) properties.get(key);
            titulos.add(valTitulo);
            key = "album";
            valAlbum = (String) properties.get(key);
            albums.add(valAlbum);
            key = "duration";
            valDuracion = ((Long) properties.get(key))/1000000;
            duraciones.add(valDuracion);
            key = "date";
            if((String)properties.get(key)!=null && !((String)properties.get(key)).equals("")){
                valAño = Integer.parseInt((String)properties.get(key));      
            }            
        }      
        // TAudioFormat properties
        if (baseFormat instanceof TAudioFormat) {
             Map properties = ((TAudioFormat)baseFormat).properties();
             key = "bitrate";
             String br = String.valueOf((Integer) properties.get(key)/1000);
             valBitrate = Long.parseLong(br);
             bitrates.add(valBitrate);
             valFrecuencia = ((long)((TAudioFormat)baseFormat).getSampleRate())/1000;
             frecuencias.add(valFrecuencia);
        }
        caratulas.add(null);
        
        //GUARDANDO EN BASE DE DATOS
//        try {
//            stmt = conn.createStatement(); 
//            String instruccion = "INSERT INTO lista VALUES("+cont+", '"+valArtista+"', '"+valTitulo+
//                    "', '"+valAlbum+"','"+null+"',"+valAño+" ,"+valBitrate+","+valFrecuencia+","+valDuracion+
//                    ","+valTamaño+",'"+valArchivo+"', '"+valRuta+"','"+null+"','"+null+"')";
//            stmt.execute(instruccion); //null: genero y compositores 
//        } catch (SQLException ex) {
//            Logger.getLogger(ReproductorFinal.class.getName()).log(Level.SEVERE, null, ex);
//        }        
        
        if(cont==1){
            track = new MP3AD(filename);            
        }
        if(lista.getSelectedIndex()==-1){
            lista.setSelectedIndex(0);
        }
    }
            
    
    private void previousActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_previousActionPerformed
        if(index > 0){
            index = lista.getSelectedIndex();
            index = index - 1;
            lista.setSelectedIndex(index);
            this.stopActionPerformed(evt);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
            }
            filename = rutas.get(index);
            track = new MP3AD(filename);
            sw2=1;
            ultimo = false;
            this.playActionPerformed(evt);
            //sw=1;
        }
    }//GEN-LAST:event_previousActionPerformed

    private void playActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_playActionPerformed
        if(sw==0) {
            if(filename.length()==0){
                pantalla.setText("ABRA UN ARCHIVO PARA REPRODUCIR");
            }
            else{
                sw=1;                
                track.play();
                //duracion = (8*pesos.get(index))/(track.getBitrate()/1000);                
                duracion = duraciones.get(index);
                reloj.setTimeTotal(duraciones.get(index));
                reloj.startCronometro();
                if(timeDesp.getMaximum()!=duracion){
                    timeDesp.setMaximum((int)duracion+5);
                }
                if(sw2==1){
                    timeDesp.setValue(0);
                    nroActual=0;
                    nroAnterior=0;
                    sw2=0;
                }
                this.avanzarDesp();
                //pantalla.setText(/*"REPRODUCIENDO  "+*/archivos.get(index));
                pantalla.setText(/*"REPRODUCIENDO  "+*/titulos.get(index));
                //play.setText("PAUSE");
                play.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pause.png")));
                equalizador.setIcon(new javax.swing.ImageIcon(getClass().getResource("/equalizador_mov.gif")));
                artista.setText(artistas.get(index));
                titulo.setText(titulos.get(index));
                album.setText(albums.get(index));
                extras.setText(frecuencias.get(index)+" kHz   "+bitrates.get(index)+" kbps");
//                if(caratulas.get(index)!=null){
//                    caratula.setText(null);
//                    caratula.setIcon(new javax.swing.ImageIcon(caratulas.get(index)));
//                }
//                else{
//                    caratula.setIcon(null);
//                    caratula.setText("IMAGEN NO DISPONIBLE");
//                }
            }
        }
        else {
            reloj.pauseaCronometro();
            this.detenerDesp();
            track.pause();
            play.setIcon(new javax.swing.ImageIcon(getClass().getResource("/play.png")));
            equalizador.setIcon(new javax.swing.ImageIcon(getClass().getResource("/equalizador_stp.png")));
            pantalla.setText(/*"PAUSADO  "+*/archivos.get(index));
        }
    }//GEN-LAST:event_playActionPerformed

    private void nextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextActionPerformed
        if(index < cont-1){
            if(aleatorio==true){
                indexAleatorio = indicesAleatorios.nextInt(cont);             
                index = indexAleatorio;
                lista.setSelectedIndex(index);
            }
            else{
                if(index!=-1){
                    index = lista.getSelectedIndex();     
                }                                               
                index = index + 1;             
                lista.setSelectedIndex(index);
            }
            /*index = lista.getSelectedIndex();
            index = index + 1;
            lista.setSelectedIndex(index);*/
            this.stopActionPerformed(evt);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
            }
            filename = rutas.get(index);
            track = new MP3AD(filename);
            sw2=1;
            if(index == cont-1){
                ultimo = true;                
            }
            this.playActionPerformed(evt);
            /*filename = tracks[index];
            track.close();
            track = new MP3AD(filename);
            track.play();
            duracion = (8*pesos[index])/(track.getBitrate()/1000);
            reloj.setTimeTotal(duracion);
            pantalla.setText("REPRODUCIENDO  "+titles[index]);
            sw=1;*/
        }
        else{
            if(aleatorio==true){
                indexAleatorio = indicesAleatorios.nextInt(cont);              
                index = indexAleatorio;
                lista.setSelectedIndex(index);
                this.stopActionPerformed(evt);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
                }
                filename = rutas.get(index);
                track = new MP3AD(filename);
                sw2=1;
                if(index == cont-1){
                    ultimo = true;                    
                }
                this.playActionPerformed(evt);
            }
        }
    }//GEN-LAST:event_nextActionPerformed

    private void stopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopActionPerformed
        reloj.stopCronometro();
        track.close();
        this.detenerDesp();
        nroActual=0;
        nroAnterior=0;
        timeDesp.setValue(0);
        play.setIcon(new javax.swing.ImageIcon(getClass().getResource("/play.png")));
        equalizador.setIcon(new javax.swing.ImageIcon(getClass().getResource("/equalizador_stp.png")));
        pantalla.setText("");
    }//GEN-LAST:event_stopActionPerformed

    private void listaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listaMouseClicked
        if(lista.getSelectedValue()!=null){
            /*//this.detenerDesp();
            track.close();
            filename = lista.getSelectedValue().toString();
            index = lista.getSelectedIndex();
            reloj.stopCronometro();
            track = new MP3AD(filename);
            track.play();
            duracion = (8*pesos[index])/(track.getBitrate()/1000);
            reloj.setTimeTotal(duracion);
            reloj.startCronometro();
            if(timeDesp.getMaximum()!=duracion){
                timeDesp.setMaximum((int)duracion);
                System.out.println(timeDesp.getMaximum());
            }
            timeDesp.setValue(0);
            nroActual=0;
            nroAnterior=0;
            this.avanzarDesp();
            pantalla.setText("REPRODUCIENDO  "+titles[index]);
            play.setText("PAUSE");
            sw=1;
            */
            this.stopActionPerformed(null);
            index = lista.getSelectedIndex();
            filename = rutas.get(index);
            if(index == cont-1){
                ultimo = true;
            }
            track = new MP3AD(filename);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
            }
            this.playActionPerformed(null);
            sw2=1;
        }
    }//GEN-LAST:event_listaMouseClicked

    private void listaValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listaValueChanged
        /*if(lista.getSelectedValue()!=null){
            //this.detenerDesp();
            track.close();
            filename = lista.getSelectedValue().toString();
            index = lista.getSelectedIndex();
            reloj.stopCronometro();
            track = new MP3AD(filename);
            track.play();
            duracion = (8*pesos[index])/(track.getBitrate()/1000);
            reloj.setTimeTotal(duracion);
            reloj.startCronometro();
            if(timeDesp.getMaximum()!=duracion){
                timeDesp.setMaximum((int)duracion);
                System.out.println(timeDesp.getMaximum());
            }
            timeDesp.setValue(0);
            nroActual=0;
            nroAnterior=0;
            this.avanzarDesp();
            pantalla.setText("REPRODUCIENDO  "+titles[index]);
            play.setText("PAUSE");
            sw=1;
        } */
    }//GEN-LAST:event_listaValueChanged

    private void timeDespMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_timeDespMouseClicked
        nroActual=timeDesp.getValue();
        //track.pause();
        //this.detenerDesp();
        //nroActual=nroActual*1000;
        //reloj.pauseaCronometro();
        if(nroActual>=nroAnterior){
            track.setTiempoBarra(1000*(nroActual/*-nroAnterior*/));
        }
        else{
            track.setTiempoBarra2(1000*(/*nroAnterior-*/nroActual));
        }
        track.play();
        reloj.setTimeActual(nroActual);  
        nroAnterior = nroActual;
        sw=1;
        //this.avanzarDesp();
    }//GEN-LAST:event_timeDespMouseClicked

    private void timeDespStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_timeDespStateChanged

    }//GEN-LAST:event_timeDespStateChanged

    private void timeDespMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_timeDespMouseDragged
        nroActual=timeDesp.getValue();
        //track.pause();
        //this.detenerDesp();
        //nroActual=nroActual*1000;
        //reloj.pauseaCronometro();
        if(nroActual>=nroAnterior){
            track.setTiempoBarra(1000*(nroActual/*-nroAnterior*/));
        }
        else{
            track.setTiempoBarra2(1000*(/*nroAnterior-*/nroActual));
        }
        track.play();
        reloj.setTimeActual(nroActual);        
        nroAnterior = nroActual;
        sw=1;
        //this.avanzarDesp();
    }//GEN-LAST:event_timeDespMouseDragged

    private void removeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeActionPerformed
        if(lista.getSelectedValue()!=null) {
            this.stopActionPerformed(evt);            
            index = lista.getSelectedIndex();
            rutas.remove(index);
            archivos.remove(index);
            artistas.remove(index);
            titulos.remove(index);
            albums.remove(index);
            frecuencias.remove(index);
            bitrates.remove(index);
            caratulas.remove(index);
            tamaños.remove(index);
            //pesos.remove(index);
            duraciones.remove(index);
            lista.setListData(archivos.toArray());
            if(index!=0){
                index-=1;
            }
            else {
                index=0;
            }
            try {
                stmt.execute("DELETE from lista where idSong = "+cont);
            } catch (SQLException ex) {
                Logger.getLogger(ReproductorFinal.class.getName()).log(Level.SEVERE, null, ex);
            }
            cont-=1;
            lista.setSelectedIndex(index);
            track = new MP3AD(rutas.get(index));
        }
    }//GEN-LAST:event_removeActionPerformed

    private void randomActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_randomActionPerformed
        if(aleatorio==false){
            aleatorio=true; 
            random.setIcon(new javax.swing.ImageIcon(getClass().getResource("/random_act.png")));
        }
        else {
            aleatorio=false;  
            random.setIcon(new javax.swing.ImageIcon(getClass().getResource("/random.png")));
        }        
    }//GEN-LAST:event_randomActionPerformed

    private void repetirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_repetirActionPerformed
        if(repetirLista==false){
            repetir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/repetir_act.png")));
            repetirLista = true;    
        }
        else{
            repetir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/repetir.png")));
            repetirLista = false;    
        }        
    }//GEN-LAST:event_repetirActionPerformed

    private void volDespMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_volDespMouseClicked
        volumen = ((float)volDesp.getValue())/100;
        Volumen.setVolumen(volumen);
    }//GEN-LAST:event_volDespMouseClicked

    private void volDespMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_volDespMouseDragged
        volumen = ((float)volDesp.getValue())/100;
        Volumen.setVolumen(volumen);
    }//GEN-LAST:event_volDespMouseDragged
    String cancion;
    private void elegirMusica_btnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_elegirMusica_btnActionPerformed
        // TODO add your handling code here:
        String Lugar = convertirSimbolo(lugar_cbx.getSelectedItem().toString());
        String TipoEvento = convertirSimbolo(tipoEv_cbx.getSelectedItem().toString());
        String Hora = convertirSimbolo(hora_cbx.getSelectedItem().toString());
        String CantPersonas = convertirSimbolo(cantPer_cbx.getSelectedItem().toString());
        String edadProm = convertirSimbolo(edadProm_cbx.getSelectedItem().toString());
        String generoMayoritario = convertirSimbolo(generoM_cbx.getSelectedItem().toString());
        
        System.out.println(Lugar + " "+ TipoEvento + " "+  Hora+ " "+ CantPersonas+ " "+  edadProm + " "+  generoMayoritario);
        try {
            motor.agregarHecho(Lugar, TipoEvento, Hora, CantPersonas, edadProm,generoMayoritario);
            filename = motor.elegirCancion();
            System.out.println(filename);
            track = new MP3AD(filename);
            agregarALista(filename);
            playActionPerformed(null);
        } catch (JessException ex) {
            Logger.getLogger(ReproductorFinal.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_elegirMusica_btnActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_jButton2ActionPerformed

    public void avanzarCancion(){   
        this.nextActionPerformed(null);
    }
    
    public void avanzarAleatorio() {
        indexAleatorio = indicesAleatorios.nextInt(cont);
        if(indexAleatorio==cont-1){
            indexAleatorio-=1;
        }
        lista.setSelectedIndex(indexAleatorio);
        this.nextActionPerformed(null);
    }
    
    public void avanzarDesp() {
        //hilo = new Thread(this);
        //hilo.start();
        new Thread() {
            @Override
            public void run(){
                while(sw==1){
                    try {
                        Thread.sleep(a);                
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    nroActual+=1;
                    timeDesp.setValue(nroActual);
                    if(nroActual >= duracion){ 
                        //if(aleatorio==true){
                            //avanzarAleatorio();
                            //nroActual=0;
                            //nroAnterior = 0;
                        //}
                        //else{
                            if(ultimo == true ){
                                if(aleatorio!=true){
                                    if(repetirLista==true){
                                        //index = lista.getSelectedIndex();
                                        index = -1;
                                        lista.setSelectedIndex(index);
                                        nextActionPerformed(null);
                                        ultimo = false;
                                    }
                                    else {
                                        stopActionPerformed(null);   
                                    }
                                }
                                else {
                                    nroActual=0;
                                    nroAnterior = 0;
                                    avanzarCancion();    
                                }
                            }
                            else {
                                nroActual=0;
                                nroAnterior = 0;                            
                                avanzarCancion();
                            }
                        }
                    }
                }    
            //}
        }.start();
    }
    
    public void detenerDesp() {
        sw=0;
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {       
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(ReproductorFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(ReproductorFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(ReproductorFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(ReproductorFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
            
        

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {                 
                try {
                    new ReproductorFinal().setVisible(true);
                } catch (JessException ex) {
                    Logger.getLogger(ReproductorFinal.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel Panel;
    private javax.swing.JLabel album;
    private javax.swing.JLabel artista;
    private javax.swing.JComboBox cantPer_cbx;
    private javax.swing.JComboBox edadProm_cbx;
    private javax.swing.JButton elegirMusica_btn;
    private javax.swing.JLabel equalizador;
    private javax.swing.JLabel extras;
    private javax.swing.JComboBox generoM_cbx;
    private javax.swing.JComboBox hora_cbx;
    private javax.swing.JLabel imagen;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JList lista;
    private javax.swing.JComboBox lugar_cbx;
    private javax.swing.JButton next;
    private javax.swing.JButton open;
    private javax.swing.JLabel pantalla;
    private javax.swing.JButton play;
    private javax.swing.JButton previous;
    private javax.swing.JButton random;
    private javax.swing.JButton remove;
    private javax.swing.JButton repetir;
    private javax.swing.JButton stop;
    private javax.swing.JSlider timeDesp;
    private javax.swing.JComboBox tipoEv_cbx;
    private javax.swing.JLabel titulo;
    private javax.swing.JSlider volDesp;
    // End of variables declaration//GEN-END:variables
    public String convertirSimbolo(String simbolo){
        if(simbolo.equals("Cumpleaños"))
            return "cumpleanios";
        if(simbolo.equals("Quinceañero"))
            return "quinceaniero";
        
        if(simbolo.equals("Masculino"))
            return "M";
        if(simbolo.equals("Femenino"))
            return "F";
        return simbolo.toLowerCase();
    }

}

